package application;

import application.thread.ClientThread;
import application.thread.PeerThread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
import window.ChatWindow;

/**
 *
 * @author Simão
 */
public class ClientApplication {

    private static HashMap<Long, PeerThread> connectionMap;
    private static HashMap<Long, ChatWindow> windowsMap;
    private static ArrayList<Long> userList;
    /* declare the rest of the shared memory */

    public static void main(String... args) {
        ServerSocket serverSocket;
        Socket socket;
        Semaphore clientSemaphore;
        System.out.println("DumbTalk Client Started.");
        clientSemaphore = new Semaphore(0);
        System.out.println("Synchronization points initialized.");
        new ClientThread(clientSemaphore).start();
        try {
            clientSemaphore.acquire();
        } catch (InterruptedException ex) {
            System.out.println("InterruptedException in synchronization point. Aborting connection.");
            return;
        }
        System.out.println("Conenction with server estabilished.");
        try {
            serverSocket = new ServerSocket(7070);
        } catch (IOException ex) {
            System.out.println("IOException in ServerSocket. Aborting client.");
            return;
        }
        System.out.println("ServerSocket sucessfully initialized.");
        loadSharedMemory();
        while (true) {
            try {
                System.out.println("Client is waiting for other peer connection requests.");
                socket = serverSocket.accept();
            } catch (IOException ex) {
                System.out.println("IOException in Socket. Connection aborted.");
                continue;
            }
            System.out.println("Connection has been estabilished.");
            new PeerThread(socket, new ChatWindow()).start();
        }
    }

    private static void loadSharedMemory() {
        connectionMap = new HashMap<>();
        windowsMap = new HashMap<>();
        userList = new ArrayList<>();
        /* initialize the rest of the shared memory */
    }

    public static synchronized void addConenction(
            long userid,
            PeerThread peerThread) {
        connectionMap.put(userid, peerThread);
    }
    
    public static synchronized boolean userExists(long userid) {
        return userList.contains(userid);
    }
    
    public static synchronized boolean connectionExists(long userid) {
        return connectionMap.containsKey(userid);
    }
    
    public static void sendStreamToUser(long userid, byte[] stream) {
        connectionMap.get(userid).useWriterList(ListOption.ADD,stream);
    }
    
    /* initialize the rest of the shared memory access methods */
}
